<?php

/**
 * Created by PhpStorm.
 * User: yifeng
 * Date: 2018/3/16
 * Time: 16:48
 */

namespace app\common\model;

use app\common\validate\User as UserValidate;
use app\common\controller\Base;
use think\Model;

class User extends Model
{
    //一对多的关联模型
    public function Users()
    {
        return $this->hasMany('Users', 'uid');
    }
    protected  $insert = ['regtime', 'salt', 'token', 'token_exptime'];
    //Md5加密码
    protected function setPasswdAttr($value)
    {
        return md5($value . md5(time()));
    }
    //自动完成注册时间
    protected function setRegtimeAttr()
    {
        return time();
    }
    //自动完成密码辅助
    protected function setSaltAttr()
    {
        return md5(time());
    }
    protected function setTokenAttr($value, $data)
    {
        $token = md5($data['account'] . $data['passwd'] . time());
        return $token;
    }
    protected function setTokenExptimeAttr()
    {
        $token_exptime = time() + 24 * 60 * 60;
        return $token_exptime;
    }
    //用户注册
    public static function userreg($data)
    {
        $userValidate = new UserValidate();
        if (!$userValidate->scene('reg')->check($data)) {
            return ['code' => 0, 'msg' => $userValidate->getError()];
        }
        $res = self::create($data, true);
        if ($res) {
            $result = Base::sendTextmail($res->email, $res->account, url('index/Index/active', '', '', true) . "?token=" . $res->token);
            return ['code' => 1, 'msg' => '注册成功,请到您注册邮箱中激活账号！'];
        }
        return ['code' => 0, 'msg' => '注册失败'];
    }

    //用户激活
    public static function active($token)
    {
        // 基本思路是, 获取token查询数据库是否存在,判断时间是否过期
        $res = self::field('token,token_exptime,account,passwd,email')->where('token', $token)->find();
        if (!$res) {
            return ['code' => 0, 'msg' => '用户不存在，请注册'];
        }
        if (time() < $res['token_exptime']) {
            $res->isactive = 1;
            $result = $res->save();
            if ($result === 0) {
                return ['code' => 1, 'msg' => '账号已激活，请登录'];
            }
            if ($result === 1) {
                return ['code' => 1, 'msg' => '激活成功，请登录'];
            }
            if ($result === false) {
                return ['code' => 0, 'msg' => '激活失败'];
            }
        }
        //激活连接有效期已过，时重新给用户发送邮件
        $newstoken = md5($res->account . $res->passwd . time());
        $time = time() + 24 * 60 * 60;
        db('user')->where('token', $token)->update(['token' => $newstoken, 'token_exptime' => $time]);
        $result = Base::sendTextmail($res->email, $res->account, url('index/Index/active', '', '', true) . "?token=" . $newstoken);
        return ['code' => 0, 'msg' => '连接已失效，新的激活连接已发送到您的邮箱，请重新激活！'];
    }
    //用户登录
    public static function login($data)
    {
        //$count =session('retry');
        $count = cache($data['account'] . 'retry');
        $userValidate = new UserValidate();
        if (!$userValidate->scene('index')->check($data)) {
            return ['code' => 0, 'msg' => $userValidate->getError()];
        }
        //验证验证码
        if ($count > 3) {
            if (!$userValidate->scene('code')->check($data)) {
                return ['code' => 3, 'msg' => $userValidate->getError(), 'count' => $count];
            }
        }
        $res = self::where('account', $data['account'])->field('uid,account,passwd,salt,isactive')->find();
        if (!$res) {
            //session('retry',$count+1);
            //            cache($data['account'].'retry',$count+1,3600);
            //            cookie('codecount',$count+1,3600);
            return ['code' => 0, 'msg' => "用户不存在"];
        }
        if ($res['isactive'] == 0) {
            return ['code' => 0, 'msg' => "用户未激活，请到注册邮箱中激活"];
        }
        if (md5($data['passwd'] . $res['salt']) != $res['passwd']) {
            //session('retry',$count+1);
            cache($data['account'] . 'retry', $count + 1, 3600);
            cookie('codecount', encrypt((string) ($count + 1), SALT), 3600);
            return ['code' => 2, 'msg' => "密码输入错误"];
        }
        return Base::setLogin($data['account'], $res['uid']);
    }

    /**
     * 账号绑定
     * @param mixed $data 账号信息
     * @return $this|void
     */
    public static function bind($data)
    {
        $validate = validate('User');
        if (!$validate->scene('bind')->check($data)) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        //判断账号是否存在
        $res_user = User::where('account', $data['account'])->find();
        $users_data = session('userinfo');
        $users_data['type'] = 1;
        if ($res_user) {
            //如果账号已存在
            $res_tmp = Users::where('type', 1)->where('uid', $res_user['uid'])->find();
            if ($res_tmp) {
                return ['code' => 0, 'msg' => "账号已绑定其它QQ用户，请重新绑定新账号！"];
            }
            //判断密码邮箱输入是否正确
            if (md5($data['passwd'] . $res_user['salt']) != $res_user['passwd'] || $data['email'] != $res_user['email']) {
                //如果不正确
                return ['code' => 0, 'msg' => "账号信息输入不正确"];
            }
            if ($res_user['isactive'] != 1) {
                $res_user->save(['isactive' => 1]);
            }
            //如果一致，直接进行账号绑定
            //            $users_data['uid']=$res_user['uid'];
        } else {
            //账号不存在
            //为用户注册新账号，直接把用户信息写入用户表
            $data['isactive'] = 1;
            $res_user = User::create($data);
            //$users_data['uid']=$user->uid;
            //查询新增用户
            //            $res_user=User::find(['uid'=>$user->uid]);
            //            $resuser->Users()->save($users_data);
        }

        //把第QQ用户写入第三方用户表
        //        Users::create($users_data);
        //使用关联模型的方式新增
        $res_user->Users()->save($users_data);
        //账号绑定成功，设置为登录状态
        return Base::setLogin($data['account']);
    }
    //密码修改
    public static function setpasswd($data)
    {
        $uservalidate = new UserValidate();
        if (!$uservalidate->scene('passwd')->check($data)) {
            return ['code' => 0, 'msg' => $uservalidate->getError()];
        }
        $user = self::get(['account' => session('username')]);
        if (md5($data['oldpasswd'] . $user['salt']) != $user['passwd']) {
            return ['code' => 0, 'msg' => '旧密码输入不正确'];
        }
        $user->passwd = $data['passwd'];
        $user->salt = "";
        $res = $user->save();
        if ($res) {
            return ['code' => 1, 'msg' => '密码修改成功'];
        }
    }
}
